package cn.magictodo.weblog.admin.schedule;

import cn.magictodo.weblog.common.domain.dos.ArticleDO;
import cn.magictodo.weblog.common.domain.mapper.ArticleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Map;

import static cn.magictodo.weblog.common.enums.RedisPrefixEnum.REDIS_ARTICLE_RADE_NUM;

/**
 * @author liu
 * @since 2023-11-27 13:33
 */
@Component
@Slf4j
public class InitRedisArticleReadNumTask {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Autowired
    private ArticleMapper articleMapper;

    @Scheduled(cron = "0 55 23 * * ?") // 每天晚间 23 点执行
    @Async("threadPoolTaskExecutor")
    public void execute() {

        // 定时任务执行的业务逻辑
        log.info("==> 开始执行初始化每日文章访问量记录定时任务");
        LocalDate now = LocalDate.now();
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(REDIS_ARTICLE_RADE_NUM.getPrefix() + now);
//        遍历数据，持久化到数据库
        entries.forEach((k, v) -> {
            Long articleId = Long.parseLong(k.toString());
            Long readNum = Long.parseLong(v.toString());
            ArticleDO articleDO = articleMapper.selectById(articleId);
            if (articleDO != null) {
                articleDO.setReadNum(articleDO.getReadNum() + readNum);
                articleMapper.updateById(articleDO);
            }

        });
//        处理完成删除数据
        redisTemplate.delete(REDIS_ARTICLE_RADE_NUM.getPrefix() + now);
        log.info("==> 结束执行初始化每日访问量记录定时任务");

    }


}
